package com.tyut.interceptors;

import com.tyut.utils.JwtUtil;
import com.tyut.utils.ThreadLocalUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import java.util.Map;

/**
 * 登录拦截器
 */
@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //令牌验证，从前端的请求头里面得到Authorization中的jwt令牌判断是否登录成功
        String token = request.getHeader("Authorization");
        
        try {
            //jwt令牌在redis中设置了过期时间，这里需要从redis中取出相关的信息判断jwt是否过期
            String redisToken = stringRedisTemplate.opsForValue().get(token);
            if(redisToken == null){
                throw new RuntimeException("token已过期");
            }
            //jwt令牌没有过期，说明登录身份有效，将jwt中的信息放入ThreadLocal中
            Map<String, Object> claims = JwtUtil.parseToken(token);
            ThreadLocalUtil.set(claims);
            return true;
        } catch (Exception e) {
            /**
             * 设置响应状态码为401，表示未登录
             */
            response.setStatus(401);
            return false;
        }
    }

    // 处理完请求后执行该方法，清理资源
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        ThreadLocalUtil.remove();
    }
}

